<template>
  <div class="advance-table-body">
    <el-form ref="form" :model="form" label-width="120px" v-loading="loading">
      <el-form-item label="版本类型">
        <div></div>
        <el-radio-group v-model="form.platform">
          <el-radio :label="'1'">windows(当前版本号 {{ windowsLastVersion }})</el-radio>
          <el-radio :label="'2'">mac(当前版本号 {{macOSLastVersion}})</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="版本号">
        <el-input style="width: 240px" v-model="form.versionNum" @input="handleInput" placeholder="请输入版本号格式,如1.0这种形式"></el-input>
      </el-form-item>
      <el-form-item label="安装文件">
        <div class="upload-box">
          <el-input style="width: 240px" v-model="form.originalFileName" disabled>
            <el-button
            slot="append"
            icon="el-icon-delete"
            @click="handleButtonClick"
          ></el-button>
          </el-input>
          <el-upload
            class="upload-demo"
            ref="upload"
            :action="fileUrl"
            name="file"
            :http-request="customUpload"
            :headers="{Authorization:authorization}"
            :on-change="handleChange"
            :on-exceed="handleExceed"
            :on-error="handleError"
            :limit="1"
            :file-list="fileList"
            :show-file-list="false"
            :auto-upload="false">
            <el-button type="primary" size="small" class="btnFile" :disabled="fileList.length!==0">选取文件</el-button>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="版本更新标题">
        <el-input style="width: 240px" v-model="form.versionTitle"></el-input>
      </el-form-item>
      <el-form-item label="版本更新内容">
        <el-input style="width: 240px" v-model="form.versionNote" type="textarea" :rows="4"></el-input>
      </el-form-item>
      <el-progress v-show="isShowProgress" class="submitProgress" :text-inside="true" :stroke-width="20" :percentage="uploadPercentage" status="success"></el-progress>
      <el-button type="primary" size="small" class="btnSubmit" @click="clickBtnSubmit">提交</el-button>
    </el-form>
    <!--<progress-hud ref="progressHudRef" :rate="uploadPercentage"></progress-hud>-->
  </div>
</template>
<script>
import request from '@/utils/request';
import { getToken } from '@/utils/auth'
import axios from 'axios'
import ProgressHud from '@/views/custom/appManage/progressHud.vue';

export default {
  components: { ProgressHud },
  data(){
    return{
      initForm:{
        platform:"1",//平台1windos2macOS
        versionTitle:null,
        versionNote:null,
        versionNum:null,
        lastVersion:null,
        url:null,
        fileSize:null,
        originalFileName:null,
      },
      form:{ },
      windowsLastVersion:null,
      macOSLastVersion:null,
      fileList:[],
      loading:false,
      uploadPercentage:0,
      isShowProgress:false,
    }
  },
  computed:{
    fileUrl(){
      return process.env.VUE_APP_BASE_API+'/common/upload';
    },
    authorization(){
      return 'Bearer ' + getToken();
    }
  },
  mounted() {
    this.form = { ...this.initForm };
    this.requestDataLast();

  },
  methods:{
    clickBtnSubmit(){
      if (!this.form.versionNum){
        this.$message.error("请输入版本号");
        return;
      }
      if (this.form.platform === "1"){
        if (!this.compareNumbers(this.form.versionNum,this.windowsLastVersion)){
          this.$message.error("输入版本号必须大于当前版本号");
          return
        }
      }else {
        if (!this.compareNumbers(this.form.versionNum,this.macOSLastVersion)){
          this.$message.error("输入版本号必须大于当前版本号");
          return;
        }
      }
      if (this.fileList.length === 0){
        this.$message.error("请选择安装文件");
        return;
      }
      if (!this.form.versionTitle){
        this.$message.error("请输入更新标题");
        return;
      }
      if (!this.form.versionNote){
        this.$message.error("请输入更新内容");
        return;
      }
      this.$refs.upload.submit();
    },
    handleButtonClick(){
      this.$refs.upload.clearFiles();
      this.fileList = [];
      this.form.originalFileName = null;
    },
    customUpload(file) {
      this.isShowProgress = true;
      this.uploadPercentage = 0;
      const formData = new FormData();
      formData.append('file', file.file); // 根据后端接收方式，这里的 'file' 是文件字段的key

      const config = {
        headers: {
          'Authorization': this.authorization,
        },
        onUploadProgress: progressEvent => {
          console.log(progressEvent.loaded)
          this.uploadPercentage = Math.round((progressEvent.loaded * 100) / progressEvent.total); // 更新上传进度
        }
      };

      axios.post(this.fileUrl, formData, config)
          .then(response => {
            // 处理成功响应
            if (response.data.code === 200) {
              this.$message.success("文件上传成功");
              this.form.url = response.data.url;
              this.form.fileSize = response.data.fileSize;
              this.requestDataSubmit();
            }else {
              this.$message.error(response.data.msg);
            }
          })
          .catch(error => {
            // 处理错误响应
            // console.error(error);
            this.$message.error(error);
          });
    },
    //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange(file, fileList){
      console.log("文件状态改变赋值前",this.fileList);
      this.fileList = fileList;
      console.log("文件状态改变赋值后",this.fileList);
      this.form.originalFileName = file.name;
    },
    //文件超出个数限制时的钩子
    handleExceed(files, fileList){
      this.$message.error("超出最大限制,请先删除")
    },
    handleError(){
      this.$message.error("文件上传失败");
    },
    //网络-新增: 版本信息
    requestDataSubmit(){
      this.loading = true;
      if (this.form.platform === "1"){
        this.form.lastVersion = this.windowsLastVersion;
      }else {
        this.form.lastVersion = this.macOSLastVersion;
      }
      if (!this.form.lastVersion){
        this.form.lastVersion = 0;
      }
      request({
        url:`/version_control`,
        method:'post',
        data: this.form,
      }).then(response =>{
        this.$message.success("提交成功");
        this.form = { ...this.initForm };
        this.fileList = [];
        this.requestDataLast();
        setTimeout(()=>{
          this.isShowProgress = false;
        },500);
      }).finally(()=>{
        this.loading = false;
      })
    },
    //网络-查询: 最新版本信息
    requestDataLast(){
      request({
        url:`/version_control/last`,
        method:'get',
        params: {  },
      }).then(response =>{
        response.rows.forEach(item=>{
          if (item.platform === "1"){
            this.windowsLastVersion = item.lastVersion;
          }
          if (item.platform === "2"){
            this.macOSLastVersion = item.lastVersion;
          }
        })
      })
    },
    //版本号输入监听
    handleInput(value){
      this.form.versionNum = value.replace(/[^0-9.]/g, '');
    },
    compareNumbers(str1,str2){
      // 去掉小数点
      if (!str2){
        str2 = '0';
      }
      if (!str1){
        str1 = '0';
      }
      const parts1 = str1.split('.');
      const parts2 = str2.split('.');
      const maxLength = Math.max(parts1.length, parts2.length);

      for (let i = 0; i < maxLength; i++) {
        const num1 = parseInt(parts1[i], 10) || 0; // 默认为 0，如果不存在
        const num2 = parseInt(parts2[i], 10) || 0; // 默认为 0，如果不存在

        if (num1 > num2) return true; // 版本1大于版本2
        if (num1 < num2) return false; // 版本1小于版本2
      }
      return false; // 版本相等
    }
  }
}

</script>

<style scoped>
.btnSubmit{
  width: 240px;
  margin-left: 120px;
}
.submitProgress{
  width: 240px;
  margin-left: 120px;
  margin-bottom: 10px;
}
.btnFile{
  margin-left: 10px;
}
.upload-box {
  display: flex;
}

</style>
